import zmq
import sys
import time


broker_ip = sys.argv[1]
# agent_id = int(sys.argv[2])
# broker_ip = '192.168.137.79'
agent_id = 1

up, down, left, right = False, False, False, False


def decode(x_rotation, y_rotation):
    # x_distance, y_distance, rotation = -50, 50, 1
    global up
    global down
    global left
    global right
    # Calculate by x_rotation, y_rotation, can be extended to velocity.
    up, down, left, right = (x_rotation > 0 and y_rotation > 0), \
                            (x_rotation > 0 and y_rotation < 0), \
                            (x_rotation < 0 and y_rotation > 0), \
                            (x_rotation < 0 and y_rotation < 0)


def main(agent_id):
    context = zmq.Context()
    publisher = context.socket(zmq.PUB)
    publisher.connect("tcp://%s:5556" % broker_ip)

    subscriber = context.socket(zmq.SUB)
    subscriber.connect("tcp://%s:5555" % broker_ip)
    subscriber.setsockopt_string(zmq.SUBSCRIBE, str(agent_id))
    while True:
        # recv data of hand moving, output to screen
        if agent_id == 1:
            message = subscriber.recv()
            # data format: float x:float y, for example: -5.5195:-9.3865
            rotation = str(message, encoding="utf8")
            # print(rotation)
            _, x_rotation, y_rotation, sender_id, x_gyro_scaled = rotation.split(':')
            print('%s:%s:%s:%s' % (sender_id, x_rotation, y_rotation, x_gyro_scaled))
            decode(float(x_rotation), float(y_rotation))  # direction vector is global.

        # wrong agent ID!
        else:
            print("wrong agent ID!")


if __name__ == "__main__":
    main(agent_id)
